package com.app.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.app.Application;
import com.app.activity.ActivityTranslucent;
import com.app.constant.Constants;
import com.app.http.HttpDataApi;
import com.app.http.HttpDataLoader;
import com.app.http.HttpDataReqUrl;
import com.app.manager.MailSender;
import com.app.model.bean.TaskBean;
import com.app.model.request.ReqObj;
import com.app.model.request.TaskReq;
import com.app.model.response.ResObj;
import com.umeng.analytics.MobclickAgent;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


public class AutoService extends Service implements HttpDataApi.OnRequestCallback, MailSender.OnSendResult {

    private static final String LOG_TAG = AutoService.class.getSimpleName();

    // 设置请求间隔为10分钟
    private long interval = 1000 * 60 * 11;

    private final String ACTION_GET_TASK = "action.get.task";

    private BroadcastReceiver receiver;

    private Timer timer;

    private HttpDataLoader dataLoader;

    private TaskBean task;

    private Handler handler;

    private final int GET_TASK = 1;


    public AutoService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // 每次服务启动的时候调用
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        Log.e(LOG_TAG, "onStartCommand");
//        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
//        long triggerAtTime = SystemClock.elapsedRealtime() + interval;
//        Intent intent2 = new Intent(AutoService.this, AutoReceiver.class);
//        PendingIntent pi = PendingIntent.getBroadcast(AutoService.this, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
//        manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
//        MobclickAgent.onEvent(this, "setAlarm");
//        receiver = new BroadcastReceiver() {
//            @Override
//            public void onReceive(Context context, Intent intent) {
//
//            }
//        };
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(ACTION_GET_TASK);
//        registerReceiver(receiver, filter);
//        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
//        long triggerAtTime = SystemClock.elapsedRealtime() + interval;
//        Intent intent2 = new Intent(AutoService.this, ActivityTranslucent.class);
//        PendingIntent pi = PendingIntent.getActivity(AutoService.this, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
//        manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);

        if (dataLoader == null) {
            dataLoader = new HttpDataLoader(this);
        }
        if (handler == null) {
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == GET_TASK) {
//                        Log.e(LOG_TAG, "time: " + TimeUtil.getFormatTime(System.currentTimeMillis(), TimeUtil.FORMAT_TIME_SECONDS));
//                        MobclickAgent.onEvent(AutoService.this, "isRunning");
                        getTask();
                    }
                }
            };
        }

        if (timer == null)  {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
//                Log.e(LOG_TAG, "time: " + TimeUtil.getFormatTime(System.currentTimeMillis(), TimeUtil.FORMAT_TIME_SECONDS));
//                MobclickAgent.onEvent(AutoService.this, "isRunning");
                    handler.sendEmptyMessage(GET_TASK);
                }
            }, interval, interval);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void getTask() {
        MobclickAgent.onEvent(AutoService.this, "getTask");
        ReqObj req = new ReqObj();
        dataLoader.POST(HttpDataReqUrl.URL_GET_TASK, req);
    }

    private void exeTask(TaskBean task) {
        MailSender.getInstance().sendMail(task);
//        , new MailSender.OnSendResult() {
//            @Override
//            public void onSendSuccess(TaskBean taskBean) {
//                SendResultUtil.getInstance().onSendSuccess(taskBean);
////                TaskReq req = new TaskReq();
////                taskBean.setExeTime(System.currentTimeMillis());
////                taskBean.setStatus(TaskBean.STATUS_SUCCESS);
////                req.setTask(taskBean);
////                dataLoader.POST(HttpDataReqUrl.URL_EXE_TASK, req);
////                Log.e(LOG_TAG, "send success");
////                Map<String, String> map_value = new HashMap<String, String>();
////                map_value.put("result", "success");
////                MobclickAgent.onEventValue(Application.instance, "exeTask" , map_value, 1);
//            }
//
//            @Override
//            public void onSendFail(TaskBean taskBean, Exception e) {
//                SendResultUtil.getInstance().onSendFail(taskBean, e);
////                TaskReq req = new TaskReq();
////                taskBean.setExeTime(System.currentTimeMillis());
////                taskBean.setStatus(TaskBean.STATUS_FAIL);
////                taskBean.setDetail(e.getMessage());
////                req.setTask(taskBean);
////                dataLoader.POST(HttpDataReqUrl.URL_EXE_TASK, req);
////                Log.e(LOG_TAG, "send fail：" + e.getMessage());
////                Map<String, String> map_value = new HashMap<String, String>();
////                map_value.put("result", "fail");
////                map_value.put("msg", e.getMessage());
////                MobclickAgent.onEventValue(Application.instance, "exeTask" , map_value, 0);
//            }
//        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(LOG_TAG, "onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        if (receiver != null) {
//            this.unregisterReceiver(receiver);
//        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        Log.e(LOG_TAG, "onDestroy");
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.e(LOG_TAG, "onConfigurationChanged");
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        Log.e(LOG_TAG, "onTrimMemory");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Log.e(LOG_TAG, "onTaskRemoved");
        Intent intent = new Intent(this, ActivityTranslucent.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
        super.dump(fd, writer, args);
        Log.e(LOG_TAG, "dump");
    }

    @Override
    public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
        Log.e(LOG_TAG, "onRequestSuccess");
        Log.e(LOG_TAG, "url: " + url);
        Log.e(LOG_TAG, "result: " + result);
        if (url.equals(HttpDataReqUrl.URL_GET_TASK)) {
            if (result.getCode() == Constants.CODE_SUCCESS) {
                if (result.getData() instanceof TaskBean) {
                    task = (TaskBean)result.getData();
                    Map<String, String> map_value = new HashMap<String, String>();
                    map_value.put("data", task.toString());
                    MobclickAgent.onEventValue(Application.instance, "getTaskResult" , map_value, 1);
                    exeTask(task);

                } else {
//                    ToastUtil.getInstance().showToast(mContext, result.getMsg());
                }
            } else {
                Map<String, String> map_value = new HashMap<String, String>();
                map_value.put("data", result.getCode() + result.getData().toString());
                MobclickAgent.onEventValue(Application.instance, "getTaskResult" , map_value, 0);
                exeTask(task);
//                ToastUtil.getInstance().showToast(mContext, result.getMsg());
            }
        }
    }

    @Override
    public void onRequestError(String url, int statusCode, String error) {
        Log.e(LOG_TAG, "onRequestError");
        Log.e(LOG_TAG, "url: " + url);
        Log.e(LOG_TAG, "statusCode: " + statusCode);
        Log.e(LOG_TAG, "error: " + error);
//        ToastUtil.getInstance().showToast(mContext, error);
    }

    @Override
    public void onSendSuccess(TaskBean taskBean) {
        TaskReq req = new TaskReq();
        taskBean.setExeTime(System.currentTimeMillis());
        taskBean.setStatus(TaskBean.STATUS_SUCCESS);
        req.setTask(taskBean);
        dataLoader.POST(HttpDataReqUrl.URL_EXE_TASK, req);
    }

    @Override
    public void onSendFail(TaskBean taskBean, Exception e) {
        TaskReq req = new TaskReq();
        taskBean.setExeTime(System.currentTimeMillis());
        taskBean.setStatus(TaskBean.STATUS_FAIL);
        taskBean.setDetail(e.getMessage());
        req.setTask(taskBean);
        dataLoader.POST(HttpDataReqUrl.URL_EXE_TASK, req);
    }
}
